use std::io;

fn main() {
    println!("Enter tasks! One per string. Empty string for a finish");

    let mut tasks: Vec<String> = Vec::new();

    let args: Vec<String> = std::env::args().collect();
    if args.len() > 0 {
        for idx in 1..args.len() {
            tasks.push(String::from(args[idx].trim()));
        }
    }

    loop {
        let mut task = String::new();
        match io::stdin().read_line(&mut task) {
            Err(_) => continue,
            Ok(_) => {
                if task.trim().len() == 0 {
                    println!("Let's go");
                    break;
                }
                tasks.push(task);
            }
        }
    }

    do_tasks(tasks);
}

fn do_tasks(mut tasks: Vec<String>) {
    let mut idx = 0;
    loop {
        if tasks.len() == 0 {
            println!("All done!! You can go home!!");
            return;
        }

        println!("Let's do: \x1b[93m{}\x1b[0m", tasks[idx]);
        println!("show next[n]/done[d]/exit[e|q]/add new task[a]");
        let mut cmd = String::new();
        match io::stdin().read_line(&mut cmd) {
            Ok(_) => {
                let c = cmd.trim();
                if c.len() != 1 {
                    continue;
                }
                match String::from(c.to_lowercase()).as_str() {
                    "n" => idx += 1,
                    "d" => {
                        tasks.remove(idx);
                    }
                    "e" => {
                        break;
                    }
                    "q" => {
                        break;
                    }
                    "a" => {
                        println!("Enter new task");
                        let mut new_task = String::new();
                        match io::stdin().read_line(&mut new_task) {
                            Ok(_) => {
                                if new_task.len() > 0 {
                                    tasks.push(new_task)
                                }
                            }
                            Err(_) => continue,
                        }
                    }
                    _ => continue,
                };
            }
            Err(_) => continue,
        }
        if idx >= tasks.len() {
            idx = 0
        }
    }
}
